import { login as loginApi, getInfo as getInfoApi } from '@/api/user'
// import router from '@/router'
import db from '@/utils/localstorage'
export default {
  namespaced: true,
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: {}
  }),
  mutations:{
    setToken(state,token){
      state.token = token
      localStorage.setItem('token', token)
    },
    setUser(state, user){
      state.user = user
    }
  },
  actions:{
    login({ commit }, userInfo){
      return new Promise((resolve, reject) => {
        loginApi(userInfo).then(res => {
          if(res.code === 0){
            commit('setToken', res.data.token)
            resolve()
          } else {
            reject()
          }
        }).catch( err => {
          reject(err)
        })
      })
    },
    getInfo({commit}){
      return new Promise((resolve, reject) => {
        getInfoApi().then(res => {
          if(res.code === 0){
            commit('setUser', res.data)
            resolve(res.data);
          }
          if (!res.data) {
            reject('用户验证失败,请重新登录.')
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    logout({ commit }){
      db.clear()
    }
  }
}